package do

import (
	"micro.room.server/common"
	"micro.room.server/database"
	"micro.room.server/models"
)

const (
	DBTable = "vs_h_room"
)

func CreateRoom(room *models.VsHRoom) error {
	eg := database.GetDB()
	if eg == nil {
		return common.DBNil
	}

	afterID, err := eg.Table(DBTable).Insert(room)
	if err != nil {
		return common.DBErr
	}
	if afterID < 1 {
		return common.DBInsertErr
	}

	return nil
}

func UpdateRoom(room *models.VsHRoom) error {
	eg := database.GetDB()
	if eg == nil {
		return common.DBNil
	}

	afterID, err := eg.Table(DBTable).ID(room.RoomId).Update(room)
	if err != nil {
		return err
	}
	if afterID < 1 {
		return common.DBErr
	}

	return nil
}

func DeleteRoom(roomIDs []uint64) error {
	eg := database.GetDB()
	if eg == nil {
		return common.DBNil
	}

	room := &models.VsHRoom{}
	afterID, err := eg.Table(DBTable).In("room_id", roomIDs).Delete(room)
	if err != nil {
		return err
	}
	if afterID < 1 {
		return common.DBErr
	}

	return nil
}

func BatchRoomInfo(roomIDs []uint64) ([]*models.VsHRoom, error) {
	eg := database.GetDB()
	if eg == nil {
		return nil, common.DBNil
	}

	rooms := make([]*models.VsHRoom, 0)

	err := eg.Table(DBTable).In("room_id", roomIDs).Find(rooms)
	if err != nil {
		return nil, err
	}

	return rooms, nil
}

func SearchRoom(req *models.SearchRoomParams) ([]*models.VsHRoom, int64, error) {
	eg := database.GetDB()
	if eg == nil {
		return nil, 0, common.DBNil
	}

	session := eg.NewSession()
	if session == nil {
		return nil, 0, common.DBNil
	}

	rooms := make([]*models.VsHRoom, 0)

	if req.HotelID > 0 {
		session.Where("hotel_id = ?", req.HotelID)
	}
	if req.RoomNo > 0 {
		session.Where("room_no = ?", req.RoomNo)
	}
	if req.Floor > 0 {
		session.Where("floor = ?", req.Floor)
	}
	if req.Price > 0.0 {
		session.Where("price = ?", req.Price)
	}
	if req.MarketPrice > 0.0 {
		session.Where("market_price = ?", req.MarketPrice)
	}
	if req.ActivityPrice > 0.0 {
		session.Where("activity_price = ?", req.ActivityPrice)
	}
	if req.IsOpen {
		session.Where("is_open = ?", req.IsOpen)
	}
	if req.RoomType != "" {
		session.Where("room_type = ?", req.RoomType)
	}

	session.Limit(int(req.Limit), int(req.Offset))

	count, err := session.Table(DBTable).FindAndCount(rooms)
	if err != nil {
		return nil, 0, err
	}

	return rooms, count, nil
}
